const express = require('express')
const fs = require('fs')
const path = require('path')
const router = express.Router()

// 获取Phonics课程列表
router.get('/lessons', (req, res) => {
  try {
    const phonicsDataPath = path.join(__dirname, '../../resources/phonics/index.json')
    const phonicsData = JSON.parse(fs.readFileSync(phonicsDataPath, 'utf8'))

    // 为每个lesson添加sounds信息
    const lessonsWithSounds = phonicsData.map((lesson) => {
      const lessonDir = path.join(__dirname, `../../resources/phonics/Lesson ${lesson.id}`)
      let sounds = []

      if (fs.existsSync(lessonDir)) {
        const soundDirs = fs.readdirSync(lessonDir)
        sounds = soundDirs.map((soundDir) => {
          // 将文件夹名称转换为大写作为显示名称
          const name = soundDir.toUpperCase()
          return {
            id: soundDir,
            name: name
          }
        })
      }

      return {
        ...lesson,
        sounds
      }
    })

    res.json(lessonsWithSounds)
  } catch (error) {
    console.error('Error reading phonics data:', error)
    res.status(500).json({ error: 'Failed to load phonics data' })
  }
})

// 获取特定课程和音素下的示例数据（包含base64数据）
router.get('/lessons/:lessonId/sounds/:soundId/examples', (req, res) => {
  try {
    const { lessonId, soundId } = req.params
    const examplesDir = path.join(__dirname, `../../resources/phonics/Lesson ${lessonId}/${soundId}`)

    if (!fs.existsSync(examplesDir)) {
      return res.status(404).json({ error: 'Lesson or sound not found' })
    }

    const exampleDirs = fs.readdirSync(examplesDir)
    const examples = exampleDirs
      .filter((dir) => fs.statSync(path.join(examplesDir, dir)).isDirectory())
      .map((exampleDir) => {
        const examplePath = path.join(examplesDir, exampleDir)

        // 获取图像base64数据
        let imageData = null
        const imagePath = path.join(examplePath, Number.parseInt(exampleDir) + '.jpg')
        if (fs.existsSync(imagePath)) {
          const imageBuffer = fs.readFileSync(imagePath)
          const base64Image = imageBuffer.toString('base64')
          imageData = `data:image/jpeg;base64,${base64Image}`
        }

        // 获取音频base64数据
        let audioData = null
        const audioPath = path.join(examplePath, Number.parseInt(exampleDir) + '.mp3')
        if (fs.existsSync(audioPath)) {
          const audioBuffer = fs.readFileSync(audioPath)
          const base64Audio = audioBuffer.toString('base64')
          audioData = `${base64Audio}`
        }

        return {
          id: exampleDir,
          name: `${exampleDir}`,
          image: imageData,
          audio: audioData
        }
      })

    res.json(examples)
  } catch (error) {
    console.error('Error reading phonics examples:', error)
    res.status(500).json({ error: 'Failed to load phonics examples' })
  }
})

module.exports = router
